﻿// JScript File
var gotMap;
var ePlayer;
var aX,aY; // Anchor x and y for upper left corner
var dX,dY; // Distance between subsequent columns/rows

var Entities; // This holds all our entities
var bLines; // This is the gameboard buffer
var MapLines; // This holds all our background lines
var MapElements; // This holds the corresponding elements on our drawn map
var DrawnLines; // This holds the world we output

function initWorld(){
    // Add some irc lines to the display
    var ChatDiv = document.getElementById('ChatBoard');
    for(i=0; i<10; i++){
	    var newLineElement = document.createElement('i' + i);
        ChatDiv.appendChild(newLineElement);
    }
    setLyr($get("BGLayer"),"ELayer");
    setLyr($get("BGLayer"),"FRLayer");
    gotMap = false;
    bLines=new Array(); // This is the gameboard buffer
    MapLines=new Array(); // This holds all our background lines
    MapElements=new Array(); // This holds the corresponding elements on our drawn map
    DrawnLines=new Array(); // This holds the world we output
    GetEntities();
}

function DrawInitialMap(){
    var GameDiv = document.getElementById('BGLayer');
    for (x in MapLines){
        var newLineElement = document.createElement('span');
        newLineElement.id="l" + x;
        newLineElement.innerHTML=MapLines[x];
        MapElements[x] = newLineElement;
        DrawnLines[x] = newLineElement;
        GameDiv.appendChild(DrawnLines[x]);
    }
    gotMap = true;
    calcXY();
    gameWorldLoop();
}

function gameWorldLoop(){
    // We need to go through the entities and draw the updated ones
    GetIRCText();
    if(gotMap==true){
        //DrawWorld();
    }
    //setTimeout('gameWorldLoop()',100);
    GetEntities();
}

function quiet(){
    // don't say anything
}
function sendError(error){
    alert('Error sending data to server');
}

function replaceChar(inString, inChar, index){
    inString = inString.replace(/&gt;/g,">");
    inString = inString.replace(/&lt;/g,"<");
    if(inString.charAt(index) == "<" && inString.substring(index).indexOf("</SPAN>") > -1){
        var spanLength = inString.substring(index).indexOf("</SPAN>");
        return inString.substring(0, index) + inChar + inString.slice((index-1)+spanLength+8);
    }else{
        return inString.substring(0, index) + inChar + inString.slice((index-1)+2);
    }
}

function keyDown(oEvent){
    //alert("keyDown");
    var oEvent = (oEvent)? oEvent : event;
    var oTarget =(oEvent.target)? oEvent.target : oEvent.srcElement; // Not worried about target YET
    //alert(oEvent.keyCode);
    var target = oEvent.target || oEvent.srcElement;
    //alert("target = " + target.id + " and " + (target.id==''))
    // 40 = down, 38 = up, 37 = left, 39 = right
    // (Numpad Below)
    // 103 104 105
    // 100 101 102
    //  97  98  99  107
    //  96 110       13
    // id = "" and tagName = "BODY" for body oTarget
    // id= "playerText" and tagName = "INPUT" for text boxed
    
    // This block processes commands meant for one of the forms
  if(oTarget.tagName=="INPUT"){
      if(oEvent.keyCode==13 && oTarget.id=="playerText"){
        if($get("playerText").value != ""){SendIRCMessage();}else{document.getElementsByTagName("BODY")[0].focus();}
        }else if(oEvent.keyCode==40 || oEvent.keyCode==38){
            document.getElementsByTagName("BODY")[0].focus();
        }
  }else if(oTarget.tagName == "BODY" || target.id == ''){
      if(oEvent.keyCode==40){
        determinePlayerAction(0,1);
      }else if(oEvent.keyCode==38){
        determinePlayerAction(0,-1);
      }else if(oEvent.keyCode==37){
        determinePlayerAction(-1,0);
      }else if(oEvent.keyCode==39){
        determinePlayerAction(1,0);
      }else if(oEvent.keyCode==84){
        $get("playerText").focus();
        $get("playerText").value = "";
        return false;
      }
   }
  
  
}

function determinePlayerAction(xoffset, yoffset){
    var moveToChar = MapLines[(ePlayer.y-1)+ 1 + yoffset].charAt((ePlayer.x - 1 ) + xoffset + 1);
    if(moveToChar == "."){
        movePlayer(xoffset,yoffset);
        //DrawWorld(); // Draw it again so we don't get ghosting
    }
}

function movePlayer(xoffset, yoffset){
        //ePlayer.lastx = ePlayer.x;
        //ePlayer.lasty = ePlayer.y;
        ePlayer.x = ePlayer.x + xoffset;
        ePlayer.y = ePlayer.y + yoffset;
        plzHalp.GameService.UpdatePlayerPos(ePlayer.x, ePlayer.y, quiet, sendError);
        var curEnt = $get('E'+ePlayer.id);
                curEnt.style.top = ((ePlayer.y) * dY) + "px";
                curEnt.style.left = ((ePlayer.x) * dX) + "px";
}

function Entity(){
    this.active = true;
    this.x = 4;
    this.y = 4;
    this.drawn = false;
    this.eChar = "R";
}

// Sort entities by y value and x value so they are drawn right-to-left and styles can be efficiently applied
function sortEntities(a,b){
    return  (b.y * 1000 + b.x) - (a.y * 1000 + a.x);
}

function GetEntities()
{
    plzHalp.GameService.GetEntities(GotEntities, FailedEntities);
}

function GotEntities(result)
{
    DrawEntities(result);
}

function FailedEntities(error){
    // Got an error, alert it up
    alert(error);
}

function GetMap()
{
    plzHalp.GameService.GetMap(0, GotMap, FailedMap);
}

function FailedMap(error){
    // Got an error, alert it up
    alert(error);
}


function GotMap(result, userContext, methodName)
{
    var output;
    gotMap = true;   
    // Page element to display feedback.
    var RsltElem = document.getElementById("ResultId");
    
    var readResult;
    for (i=0;i<result.length;i++){
        MapLines[i] = result[i] + "<BR>";
    }
	
	DrawInitialMap();
}

function findPos(obj) {
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		curleft = obj.offsetLeft
		curtop = obj.offsetTop
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft
			curtop += obj.offsetTop
		}
	}
	return [curleft,curtop];
}

function setLyr(obj,lyr)
{
	var coors = findPos(obj);
	var x = document.getElementById(lyr);
	x.style.top = coors[1] + 'px';
	x.style.left = coors[0] + 'px';
}

function calcXY(){
    dY = findPos($get('l2'))[1] - findPos($get('l1'))[1];
    dX = (findPos($get('t2'))[0] - findPos($get('t1'))[0]) + 1;
}


function DrawEntities(result){
    var output;
    // Check if we've got an array yet
    if(Entities==null){
    	Entities = new Array();
    } 
    
    // Need to add all the entities in the result array to the current list
    // and track which one relates to the current player
        for (i=0;i<result.length;i++){
            var e = result[i].ID;
            if(Entities[e]==null){
                Entities[e] = new Entity();
            }
            Entities[e].active = true;
            Entities[e].drawn = false;
            Entities[e].eChar = result[i].eChar;
            Entities[e].type =  result[i].eType;
            if(Entities[e].type != 4){
                Entities[e].x = Math.abs(result[i].X);
                Entities[e].y = Math.abs(result[i].Y);
            }else if(Entities[e].type == 4){
                //Entities[i].x = Math.abs(result[i].X);
                //Entities[i].y = Math.abs(result[i].Y);
                ePlayer = Entities[e];
                ePlayer.id = e;
            }
            var curEnt = $get('E'+e);
            if(curEnt==null){
                Entities[e].x = Math.abs(result[i].X);
                Entities[e].y = Math.abs(result[i].Y);
                curEnt = document.createElement('span');
                curEnt.id = ('E' + e);
                curEnt.style.position = 'absolute';
                //curEnt.style.backgroundColor = '#000000';
                curEnt.innerHTML = Entities[e].eChar;
                $get('ELayer').appendChild(curEnt);
            }else{
                if(curEnt.innerHTML != Entities[e].eChar) curEnt.innerHTML = Entities[e].eChar;
            }
            if(dX != null && dY != null && curEnt != null && Entities[e].type != 4){
                curEnt.style.top = ((Entities[e].y) * dY) + "px";
                curEnt.style.left = ((Entities[e].x) * dX) + "px";
            }            
        }
	

	// If we haven't drawn the map for a new board yet we need to get that
	if(gotMap==false){
        //ePlayer.lastx = ePlayer.x;
        //ePlayer.lasty = ePlayer.y;
	    GetMap();
	}
    setTimeout('gameWorldLoop()',200);
}